// miniprogram/pages/patient/patient.js
Date.prototype.format = function (fmt) {
  var o = {
    "M+": this.getMonth() + 1,                 //月份 
    "d+": this.getDate(),                    //日 
    "h+": this.getHours(),                   //小时 
    "m+": this.getMinutes(),                 //分 
    "s+": this.getSeconds(),                 //秒 
    "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
    "S": this.getMilliseconds()             //毫秒 
  };
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
  }
  for (var k in o) {
    if (new RegExp("(" + k + ")").test(fmt)) {
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    }
  }
  return fmt;
}

let thisPage = {}
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    symptom: [{
        value: '发热（＞37.3）'
      },{
        value: '咳嗽'
      }, {
        value: '胸闷'
      }, {
        value: '呼吸困难'
      }, {
        value: '腹泻'
      }, {
        value: '乏力'
      }, {
        value: '肌肉酸痛'
      }
    ],
    needs: ["住院", "用药指导", "心里支持"],
    needsIndex: 0,

    countries: ["中国", "美国", "英国"],
    countryIndex: 0,

    caseDetail:{
      name:'',
      phone:'',
      location:'',
      illDate: new Date().format("yyyy-MM-dd"),
      need:0,
      symptom:'',
      treatment:'',
      imgs: [],
      imgsUrl:[]
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    thisPage =this
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  onDateChange:function(e){
    this.setData({
      ['caseDetail.illDate']:e.detail.value
    });
  },

  onNeedChange:function(e){
    this.setData({
      needsIndex: e.detail.value
    });
  },
  // 上传图片
  doUpload: function () {
    // 选择图片
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res)=> {
        wx.showLoading({
          title: '上传中',
        })

        const filePath = res.tempFilePaths[0]
        // 上传图片
        const cloudPath = 'my-image' + filePath.match(/\.[^.]+?$/)[0]
        wx.cloud.uploadFile({
          cloudPath,
          filePath,
          success: res => {
            console.log('[上传文件] 成功：', res, filePath)
            thisPage.setData({
              ['caseDetail.imgs']: thisPage.data.caseDetail.imgs.concat(filePath),
              ['caseDetail.imgsUrl']: res.fileID
            })
          },
          fail: e => {
            console.error('[上传文件] 失败：', e)
            wx.showToast({
              icon: 'none',
              title: '上传失败',
            })
          },
          complete: () => {
            wx.hideLoading()
          }
        })

      },
      fail: e => {
        console.error(e)
      }
    })
  },

  onSymptomChange: function (e) {
    let symptom = this.data.symptom, values = e.detail.value;
    symptom.forEach(item=>{
      item.checked = false;
      values.forEach(checkValue=>{
        if (item.value==checkValue) {
          item.checked=true
        }
      })
    })
    this.setData({
      symptom: symptom
    });
  },

  formSubmit:function(e){
    let caseDetail = e.detail.value
    caseDetail.illDate=this.data.caseDetail.illDate
    caseDetail.imgs=this.data.caseDetail.imgsUrl
    caseDetail.need = this.data.needs[this.data.needsIndex]
    caseDetail.state = '未接诊'
    caseDetail.symptom=[]
    this.data.symptom.forEach((item)=>{
      if (item.checked) caseDetail.symptom.push(item.value)
    })
    caseDetail.reporter = app.globalData.openid
    wx.showLoading()
    app.globalData.cases.add({
      data: caseDetail,
      success: res => {
        wx.redirectTo({
          url: 'caseList',
        })
      },
      fail: e => {
        wx.showToast({
          icon: 'none',
          title: '提交失败，请重试',
        })
      },
      complete: () => {
        wx.hideLoading()
      }

    })

  }
})